<template>
  <div>
    <v-alert
      v-if="status.healthy===lanChar.status.HealthNotConnect"
      icon="mdi-cog mdi-light mdi-inactive"
      :color="hintColor"
      dark
      dense
      class="mt-4"
    >
      {{ healthyText }}
    </v-alert>
    <v-alert
      v-else
      icon="mdi-cog mdi-light mdi-spin"
      :color="hintColor"
      dark
      dense
      class="mt-4"
    >
      {{ healthyText }}
    </v-alert>
  </div>
</template>

<script>
  import globalDef from '@/util/globals'
  import lan from '@/util/lan-char'
  import * as axios from '@/util/apptplaxios'
  import { get, sync } from 'vuex-pathify'

  export default {
    name: 'DefaultStatus',

    data: () => ({
      lanChar: lan.GetLan(),
      STATUS_HEALTHY_INVALID: globalDef.STATUS_HEALTHY_INVALID,

      statusTimer: 0,
      status: {
        healthy: '',
      },
    }),

    computed: {
      healthyText: function () {
        return this.status.healthy
      },
      hintColor: function () {
        switch (this.status.healthy) {
          case this.lanChar.status.HealthNotConnect:
            return '#FF9800'
          case this.lanChar.status.HealthConnected:
            return '#4CAF50'
          case this.lanChar.status.HealthNotLogin:
            return '#FF9800'
          case this.lanChar.status.HealthFine:
            return '#4CAF50'
          default:
            return '#000000'
        }
      },
      ...get('user', [
        'token',
        'username',
        'password',
      ]),
      ...sync('user', [
        'connect',
        'login',
      ]),
    },

    watch: {
    },

    beforeDestroy () {
      clearInterval(this.statusTimer)
    },

    created () {
      this.reflashStatus()
      this.startReflash()
    },
    mounted () {
    },
    methods: {
      reflashStatus () {
        this.checkConn()
      },
      startReflash () {
        clearInterval(this.statusTimer)
        this.statusTimer = setInterval(this.reflashStatus, 5000)
      },
      setStatus () {
        if (this.connect) {
          if (this.login) {
            this.status.healthy = this.lanChar.status.HealthFine
          } else {
            this.status.healthy = this.lanChar.status.HealthNotLogin
          }
        } else {
          this.status.healthy = this.lanChar.status.HealthNotConnect
        }
      },
      async checkConn () {
        const data = {
          msgHead: {
            instanceID: 'apptpl-web-ui-client',
            requestType: 'heartbeat check',
            serialNum: 0,
          },
        }
        axios.axiosCheckHeartbeat(data, this.token)
          .then((res) => {
            if (res.data.msgHead.status === 'ok') {
              this.login = true
            } else {
              this.login = false
            }
            this.connect = true
            this.setStatus()
          })
          .catch((e) => {
            this.connect = false
            this.setStatus()
          })
      },
    },
  }
</script>
